package com.qk.management.web.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.qk.constant.RouterConstant;
import com.qk.entity.User;
import com.qk.management.config.UserThreadLocal;
import com.qk.properties.JwtProperties;
import com.qk.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Author:zhengbowen
 * @Date: 2025/10/11 14:34
 * @Description: JWT拦截器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtInterceptor implements HandlerInterceptor {

    private final JwtProperties jwtProperties;
    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {
        log.info("----------------------------------------------pre---------------------------------------------------");
        if (!(ObjectUtil.equals(request.getRemoteAddr(), "127.0.0.1")|| ObjectUtil.equals(request.getRemoteAddr(), "0:0:0:0:0:0:0:1"))) {
            log.info("获取发送请求方的主机名,{}", request.getRemoteHost());
            log.info("请求的url,{}", request.getRequestURI());
            log.info("请求的Ip地址非本地Ip, 拒绝访问, 401");
            return false;
        }
        if (ObjectUtil.equals(request.getRequestURI(), RouterConstant.USER_LOGIN)) {
            return true;
        }
        String token = request.getHeader(RouterConstant.TOKEN_HEADER_NAME);
        if (token == null || token.isEmpty()) {
            log.info("请求头中没有 token, 拒绝访问, 401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        try {
            Claims claims = JwtUtils.parseJWT(jwtProperties.getSecretKey(), token);
            Integer id =Integer.parseInt(claims.get("id").toString());
            User user = new User();
            user.setId(id);
            UserThreadLocal.set(user);

        } catch (Exception e) {
            log.info("解析 token 出错, 拒绝访问, 401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        log.info("token 正确, 继续执行后续处理");
        return true;
    }

    @Override
    public void afterCompletion(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler, Exception ex) {
        log.info("----------------------------------------------after---------------------------------------------------");
        UserThreadLocal.remove();
    }
}
